﻿/*
 * JQuery jGrid 1.0.1-beta
 *
 * Copyright (c) 2011  Jamie (http://code.google.com/p/jqueryjgrid/)
 *
 * Licensed same as jquery - under the terms of either the MIT License or the GPL Version 2 License
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * email: bjjiemy@163.com  jiemyonline.blog.sohu.com
 * Date: 2011-08-15
 */
;(function($){
	var BUTTON_ADD_TEXT="添加";
	var BUTTON_UPDATE_TEXT="修改";
	var BUTTON_REMOVE_TEXT="删除";
	var BUTTON_SEARCH_TEXT="搜索";
	var BUTTON_REMOVE_ALL_TEXT="全删";
	var CUSTOM_BUTTON_CLASS_NAME="custom";	
	var ODD_CLASS_NAME="odd";
	var EVEN_CLASS_NAME="even";
	var HOVER_ROW_CLASS_NAME="hover";
	var SELECTED_ROW_CLASS_NAME="click";
	var ADD_CLASS_NAME="add";
	var UPDATE_CLASS_NAME="update";
	var REMOVE_CLASS_NAME="remove";	
	var TRASH_CLASS_NAME="trash";
	var SEARCH_CLASS_NAME="search";	
	var BUTTON_HOVER_CLASS_NAME="buttonHover";	
	var THEAD_TR_HOVER_CLASS_NAME="sort";	
	var TBODY_TR_HOVER_CLASS_NAME="hover";	
	var ORDER_ASC_CLASS_NAME="sort-asc";	
	var ORDER_DESC_CLASS_NAME="sort-desc";				
	var LOADING_CLASS_NAME="jGrid_loading_class";
	var JPAGINATION_CLASS_NAME="jPagination";
	var ADD_CLICK="ADD_CLICK";
	var UPDATE_CLICK="UPDATE_CLICK";
	var REMOVE_CLICK="REMOVE_CLICK";
	var REMOVE_ALL_CLICK="REMOVE_ALL_CLICK";
	var SEARCH_CLICK="SEARCH_CLICK";
	var SELECTED_ATTR="selected";
	var BEAN_ID="beanId";
	var TH_COL_INDEX="sortIndex";		
	
	var PAGE_SIZE=10;
	var CUR_PAGE=0;
	var PREV_TEXT="上页";
	var NEXT_TEXT="下页";
	var FIRST_TEXT="首页";
	var LAST_TEXT="末页";
	var GO="跳页";
	var SHOW_STYLE_MANY_PAGE_NUMBER;
	var SHOW_STYLE_STANDARD;
	var	LOAD_DATA_SUCCESS="LOAD_DATA_SUCCESS";
	var	LOAD_DATA_ERROR="LOAD_DATA_ERROR";
	var	PAGINATION_CLICK="PAGINATION_CLICK";
	var	GO_TO_CLICK="GO_TO_CLICK";
	var	ASYNC_PAGINATION_CLICK="ASYNC_PAGINATION_CLICK";
	var	ASYNC_GO_TO_CLICK="ASYNC_GO_TO_CLICK";
	var CSS_GO_TO_PAGE="go";
	var CSS_PAGE_NUMBER="pageNumber";	
	var options_array = new Array();	
    $.fn.jGrid=function(vOption){
		var option={
			columns: [],
			height:150,
	      	width:750,
			title:"jGrid demo",
			buttons:{
				add:{text:BUTTON_ADD_TEXT,show:true},
				update:{text:BUTTON_UPDATE_TEXT,show:true},
				remove:{text:BUTTON_REMOVE_TEXT,show:true},
				search:{text:BUTTON_SEARCH_TEXT,show:true},
				removeAll:{text:BUTTON_REMOVE_ALL_TEXT,show:true},
				prev:{text:PREV_TEXT,show:true},
				next:{text:NEXT_TEXT,show:true},
				first:{text:FIRST_TEXT,show:true},
				last:{text:LAST_TEXT,show:true},
				go:{text:GO,show:true}
			},	
			customButtons:null,	
			scroll:true,
			oddRowClassName:ODD_CLASS_NAME,
			evenRowClassName:EVEN_CLASS_NAME,
			hoverRowClassName:HOVER_ROW_CLASS_NAME,				
			selectedRowClassName:SELECTED_ROW_CLASS_NAME,						
			jPaginationId:"",			
			showButtonBar:true,
			show_jPagination:true,
			show_jTable:true,
			sn:{show:false,width:50,text:"序号"},
			store:[],
			pageSize:PAGE_SIZE,
			curPage:CUR_PAGE,
			totalPageCount:1,
			totalRecordCount:0,
			pageButtonCount:10,
			curPageName:"curPage",
			pageSizeName:"pageSize",
			showStyle:SHOW_STYLE_MANY_PAGE_NUMBER,
			showPageInputText:false,
			showPageInputSelect:false,	
			goToPage:null,
			formId:null,
			formAction:"",
			formMethod:"POST",
			form:null,
			params:null,
			async:false,
			asyncUrl:"",
			asyncParams:null,			
			callback:{
				addClick:null,
				updateClick:null,
				removeClick:null,
				removeAllClick:null,
				searchClick:null,
				
				asyncSuccess:null,
				asyncError:null,
				click:null,
				goToClick:null,
				asyncClick:null,
				asyncGotoClick:null
			}			
		}
		if(vOption){
			$.extend(option, vOption);
			var tmp_callback = vOption.callback;
			if(tmp_callback){
			  vOption.callback = undefined;
			  $.extend(option.callback, tmp_callback);			
			}
			var tmp_buttons = vOption.buttons;
			if(tmp_buttons){
			  vOption.buttons = undefined;
			  $.extend(option.buttons, tmp_buttons);
			}
			var tmp_sn = vOption.sn;
			if(tmp_sn){
			  vOption.sn = undefined;
			  $.extend(option.sn, tmp_sn);
			}
			if(option.formId){
				var $form=$("#"+option.formId);
				$form.attr("action",(option.formAction=="")?$form.attr("action"):option.formAction);
				$form.attr("method",(option.formMethod=="")?$form.attr("method"):option.formMethod);
				option.form=$form;	
			}
		}	
				
		option.jGrid=this;
		option.jGrid.ajaxing=false;
		option.gridObjId = this.attr("id");		
		option.tbody=null;
		option.jGrid.SORT_FLAG=false;
	    option.contentDiv=null;		
		if(option.jPaginationId=="")option.jPaginationId=option.gridObjId+"_pagination";	
			
		initContainer(option,this);
		options_array[option.gridObjId] = option;					
		bindTableEvent(option,this); 		
		
		var jGrid=new JGrid();
		jGrid.init(this,option);
		return jGrid;
		
	};
	function initContainer(option,jGrid){		
		if(option.show_jTable){
			initColumns(option,this);
			renderTable(option,this);
			option.loading=$("#"+option.gridObjId+" ."+LOADING_CLASS_NAME);		
			option.loading.css("width",option.width-2);			
		}else if(option.show_jPagination){
			option.jGrid.append(drawJPagination(option));
		}
		if (option.async && option.asyncUrl && option.asyncUrl.length > 0) {
			asyncGetData(option);
		}		
		if(option.show_jTable){
			fillData(option);
			setEvenOddTrCss(option);	
		}				
		if(option.show_jPagination){
			option.page=$("#"+option.jPaginationId);			
			renderPage(option,option.page);			
		}					
	}
	function bindTableEvent(option,gridObj){
		var eventParam = {gridObjId: option.gridObjId};
		option.jGrid.unbind('click', eventProxy);
		option.jGrid.bind('click', eventParam, eventProxy);
		option.jGrid.unbind('mouseover', eventProxy);
		option.jGrid.bind('mouseover', eventParam, eventProxy);
		option.jGrid.unbind('mouseout', eventProxy);
		option.jGrid.bind('mouseout', eventParam, eventProxy);				
		gridObj.unbind(ADD_CLICK);
		gridObj.bind(ADD_CLICK, function (event, msg) {
			tools.apply(option.callback.addClick, [event, msg]);
		});
		gridObj.unbind(UPDATE_CLICK);
		gridObj.bind(UPDATE_CLICK, function (event, selectedIds, msg) {
			tools.apply(option.callback.updateClick, [event, selectedIds, msg]);
		});		
		gridObj.unbind(REMOVE_CLICK);
		gridObj.bind(REMOVE_CLICK, function (event, selectedIds, msg ) {
			tools.apply(option.callback.removeClick, [event, selectedIds, msg]);
		});		
		gridObj.unbind(SEARCH_CLICK);
		gridObj.bind(SEARCH_CLICK, function (event, msg) {
			tools.apply(option.callback.searchClick, [event, msg]);
		});
		
		gridObj.unbind(GO_TO_CLICK);
		gridObj.bind(GO_TO_CLICK, function (event, gridId, obj, msg) {
			tools.apply(option.callback.goToClick, [event, gridId, obj, msg]);
		});
		gridObj.unbind(PAGINATION_CLICK);
		gridObj.bind(PAGINATION_CLICK, function (event, gridId, obj, msg) {
			tools.apply(option.callback.click, [event, gridId, obj, msg]);
		});		
		gridObj.unbind(LOAD_DATA_SUCCESS);
		gridObj.bind(LOAD_DATA_SUCCESS, function (event, gridId, obj, msg, datas) {
			tools.apply(option.callback.asyncSuccess, [event, gridId, obj, msg, datas]);
		});
		gridObj.unbind(LOAD_DATA_ERROR);
		gridObj.bind(LOAD_DATA_ERROR, function (event, gridId, obj, XMLHttpRequest, textStatus, errorThrown) {
			tools.apply(option.callback.asyncError, [event, gridId, obj, XMLHttpRequest, textStatus, errorThrown]);
		});		
	}
	function renderPage(option,pageObj){
		var pagePanel=processPageHtml(option);
		option.page.html(pagePanel);		
	}
	function renderTable(option){		
		jGrid=option.jGrid;
		jGrid.addClass("listContainer");
		var html=drawTitle(option);
		html+=drawButtonBar(option);
		html+=drawHeader(option);
		html+=drawContent(option);
		html+=drawJPagination(option);		
		jGrid.html(html);
		jGrid.css("width",option.width);
		if(!option.contentDiv)option.contentDiv=$("#"+option.gridObjId+" .listContent");
		$contentDiv=option.contentDiv;
		if(option.scroll)	
			$contentDiv.css("overflow-y","scroll");
		else
			$contentDiv.css("overflow-y","hidden");		
		$("#"+option.gridObjId+" .tableList,#"+option.gridObjId+" .tableListHeader").css("width",option.width);
		$("#"+option.gridObjId+" .listTitle,#"+option.gridObjId+" .listButton").css("width",parseInt(option.width)-4);
		$contentDiv.css({"width":0+option.width,"height":0+option.height});		
		fillData(option);
	}	
	function eventProxy(event) {
		var target = event.target;
		var $target = $(target);
		var $tP=$target.parent();	
		var option = options_array[event.data.gridObjId];	
		if (tools.eqs(event.type, "click")) {
			if (tools.eqs(target.tagName, "TD")) {				
				handler.tdClick(event);				
			}else if(tools.eqs(target.tagName,"input")){
				if($target.hasClass(ADD_CLASS_NAME))
					handler.addClick(event);
				else if($target.hasClass(UPDATE_CLASS_NAME)){
					event.data.selectedIds=getSelectedIds(option);
					handler.upateClick(event);
				}else if($target.hasClass(REMOVE_CLASS_NAME)){
					event.data.selectedIds=getSelectedIds(option);
					handler.removeClick(event);
				}else if($target.hasClass(TRASH_CLASS_NAME)){
					event.data.selectedIds=getAllSelectedIds(option);
					handler.removeClick(event);
				}else if($target.hasClass(SEARCH_CLASS_NAME)){
					handler.searchClick(event);
				}
			}else if(tools.eqs(target.tagName,"DIV")&&tools.eqs($tP[0].tagName,"TH")&&$tP.children().first().is(target)){
				if($tP.attr("sn")=="true")return;
				if(!option.tbody)option.tbody=option.contentDiv.find("tbody:eq(0)");
				var colIndex=$tP.attr(TH_COL_INDEX);
				if(!colIndex||colIndex==""){
					alert("Not found attribute [sortIndex] in <TH>.");
					return;
				}
				var index=parseInt($tP.attr(TH_COL_INDEX));				
				var vTh=option.columns[index];
				if(!vTh.sortable) return ;
				if(vTh.columnIndex!=index)
				    vTh.columnIndex=index;
				event.data.thColObj=vTh;
				handler.sortDivClick(event);
			} else if(tools.eqs($target[0].tagName,"TH")){
				if($target.attr("sn")=="true")return;
				if(!option.tbody)option.tbody=option.contentDiv.find("tbody:eq(0)");
				var colIndex=$target.attr(TH_COL_INDEX);
				if(!colIndex||colIndex==""){
					alert("Not found attribute [sortIndex] in <TH>.");
					return;
				}
				var index=parseInt($target.attr(TH_COL_INDEX));				
				var vTh=option.columns[index];
				if(!vTh.sortable) return ;
				if(vTh.columnIndex!=index)
				    vTh.columnIndex=index;
				event.data.thColObj=vTh;
				handler.sortThClick(event);
			}else if (tools.eqs(target.tagName, "a") && $target.attr("class")==CSS_PAGE_NUMBER) {				
				if(option.async)
					handler.onAsyncClick(event);
				else
					handler.onClickPage(event);
			} else if (tools.eqs(target.tagName, "a") && $target.attr("class")==CSS_GO_TO_PAGE) {
				if(option.async)
					handler.onAsyncGotoClick(event);
				else
					handler.onGoToClick(event);
			}	
		} else if(tools.eqs(event.type, "mouseover")){
			if (tools.eqs(target.tagName, "INPUT") && tools.eqs($target.attr("type"), "BUTTON")) {
				handler.mouseOverButton(event);
			}else if (tools.eqs(target.tagName, "TH")&&target.getAttribute("sn")!="true"&&target.getAttribute("sortable")=="true") {
				handler.mouseOverTh(event);
			}else if (tools.eqs(target.tagName, "TD")) {
				handler.mouseOverTd(event);
			}else if(tools.eqs(target.tagName,"DIV")&&tools.eqs($tP[0].tagName,"TH")&&$tP.children().first().is(target)&&$tP.attr("sortable")=="true"){
				handler.mouseOverThDiv(event);
			}
		} else if(tools.eqs(event.type, "mouseout")){
			if (tools.eqs(target.tagName, "INPUT") && tools.eqs($target.attr("type"), "BUTTON")) {
				handler.mouseOutButton(event);
			}else if (tools.eqs(target.tagName, "TH")) {
				handler.mouseOutTh(event);
			}else if (tools.eqs(target.tagName, "TD")) {
				handler.mouseOutTd(event);
			}else if(tools.eqs(target.tagName,"DIV")&&tools.eqs($tP[0].tagName,"TH")&&$tP.children().first().is(target)){
				handler.mouseOutThDiv(event);
			}
		}
	}
	var handler = {		
		tdClick:function(event){
			var target = event.target;
			var $target = $(target);
			var $tP=$target.parent();				
			if($tP.hasClass(SELECTED_ROW_CLASS_NAME)){
			  $tP.removeClass(SELECTED_ROW_CLASS_NAME);
			  $tP.removeAttr(SELECTED_ATTR);
			}
			else{
			  $tP.addClass(SELECTED_ROW_CLASS_NAME);
			  $tP.attr(SELECTED_ATTR,"true");
			}
		},
		addClick:function(event){
			var option = options_array[event.data.gridObjId];
			option.jGrid.trigger(ADD_CLICK);
		},
		upateClick:function(event){
			var option = options_array[event.data.gridObjId];
			option.jGrid.trigger(UPDATE_CLICK,event.data.selectedIds);
		},
		removeClick:function(event){
			var option = options_array[event.data.gridObjId];
			option.jGrid.trigger(REMOVE_CLICK,event.data.selectedIds);
		},
		searchClick:function(event){
			var option = options_array[event.data.gridObjId];
			option.jGrid.trigger(SEARCH_CLICK);
		},
		sortDivClick:function(event){
			var option = options_array[event.data.gridObjId];
			var target = event.target;
			var $target = $(target);
			var $tP=$target.parent();	
			
			var thColObj=event.data.thColObj;
			sortTable(option,thColObj.columnIndex,thColObj.dataType);	
			if(!option.jGrid.SORT_FLAG){
				$target.removeClass("sort-asc").addClass("sort-desc");					  
			} else{
				$target.removeClass("sort-desc").addClass("sort-asc");					  
			}
			$tP.siblings().find("div:first").removeClass("sort-desc sort-asc");	
			setEvenOddTrCss(option);						
		},
		sortThClick:function(event){
			var option = options_array[event.data.gridObjId];
			var target = event.target;
			var $target = $(target);
			var $Div=$target.children().first();	
			
			var thColObj=event.data.thColObj;
			sortTable(option,thColObj.columnIndex,thColObj.dataType);	
			if(!option.jGrid.SORT_FLAG){
				$Div.removeClass("sort-asc").addClass("sort-desc");					  
			} else{
				$Div.removeClass("sort-desc").addClass("sort-asc");					  
			}
			$target.siblings().find("div:first").removeClass("sort-desc sort-asc");	
			setEvenOddTrCss(option);						
		},
		mouseOverButton:function(event){
			var $target = $(event.target);
			$target.addClass(BUTTON_HOVER_CLASS_NAME);
		},
		mouseOutButton:function(event){
			var $target = $(event.target);
			$target.removeClass(BUTTON_HOVER_CLASS_NAME);
		},
		mouseOverTh:function(event){
			var $target = $(event.target);					
			if(!$target.children().first().is("DIV"))
				$target.wrapInner("<DIV></DIV>");
			else
				$target.addClass(THEAD_TR_HOVER_CLASS_NAME);				
		},
		mouseOutTh:function(event){
			var $target = $(event.target);
			$target.removeClass(THEAD_TR_HOVER_CLASS_NAME);
		},
		mouseOverTd:function(event){
			var $target = $(event.target);
			var $tP=$target.parent();
			$tP.addClass(TBODY_TR_HOVER_CLASS_NAME);
		},
		mouseOutTd:function(event){
			var $target = $(event.target);
			var $tP=$target.parent();
			$tP.removeClass(TBODY_TR_HOVER_CLASS_NAME);
		},
		mouseOverThDiv:function(event){
			var $target = $(event.target);
			var $tP=$target.parent();
			$tP.addClass(THEAD_TR_HOVER_CLASS_NAME);				
		},
		mouseOutThDiv:function(event){
			var $target = $(event.target);
			var $tP=$target.parent();
			$tP.removeClass(THEAD_TR_HOVER_CLASS_NAME);				
		},
		onAsyncClick:function(event){
			var option = options_array[event.data.gridObjId];
			var $target = $(event.target);
			option.curPage=$target.attr("page");
			asyncGetData(option);
			fillData(option);
			renderPage(option);	
		},
		onAsyncGotoClick:function(event){
			var option = options_array[event.data.gridObjId];
			pageNumTxt=validatePageNumber(option);
			if(pageNumTxt==-1)return false;
			option.curPage=pageNumTxt;
			asyncGetData(option);
			fillData(option);
			renderPage(option);	
		},
		onClickPage: function (event) {
			var option = options_array[event.data.gridObjId];			
			if(!fillForm(event,option,false)) return;			
			if(option.callback.click && (typeof option.callback.click=="function")){
			  option.jGrid.trigger(PAGINATION_CLICK, [option.jGridObjId]);
			}else{				
				$form.submit();
			}				
		},
		onGoToClick: function (event) {
			var option = options_array[event.data.gridObjId];						
			if(!fillForm(event,option,true)) return;
			if(option.callback.goToClick && (typeof option.callback.goToClick=="function")){
			  option.jGrid.trigger(GO_TO_CLICK, [option.jGridObjId]);
			}else{
				$form.submit();
			}				
		}
	}
	function initColumns(option,jGrid){
		var columns=option.columns;
		if(!columns||columns.length==0){alert("option.columns is empty!");return false;}
		$.each(columns,function(i){
			this.columnIndex=i;
			if(this.id)
			  option.jGrid.idMapping=this.mapping;
		});
		return true;		
	}
	function processHeader(option){
		var cols=option.columns;
		if(!cols||cols.length==0){alert("option.columns is empty!"); return "";}
		else 
		  option.jGrid.columnCount=cols.length;
		var ret='';
		if(option.sn&&option.sn.show)
		  ret+='<th sn="true" width="'+option.sn.width+' scope="col">'+option.sn.text+'</th>';
		for(var i in cols){
			ret+='<th width="'+cols[i].width+'" '+(cols[i].sortable?"sortable=\"true\"":"")+' scope="col" sortIndex="'+i+'" ><DIV>'+cols[i].header+'</DIV></th>';
		}		
		return ret;
	}
	function asyncGetData(option, obj) {
	    if(option.jGrid.ajaxing)return null;
				
		var $loading=option.loading;
		if($loading)
			$loading.show();
		option.jGrid.ajaxing=true;
		var tmpParam = option.asyncParams;
		var pageParam={};
		var vCurPage=option.curPage;
		var vPageSize=option.pageSize;
		pageParam[option.curPageName]=vCurPage;
		pageParam[option.pageSizeName]=vPageSize;
		if(tmpParam)
			$.extend(pageParam,tmpParam);
		
		$.ajax({
			type: "POST",
			url: tools.apply(option.asyncUrl, [obj], option.asyncUrl),
			data: pageParam,
			dataType: "text",
			async:false,
			success: function(msg) {
				var newDatas = [];
				try {
					if (!msg || msg.length == 0) {
						newDatas = [];
					} else if (typeof msg == "string") {
						newDatas = eval("(" + msg + ")");
					} else {
						newDatas = msg;
					}
				} catch(err) {}
				if (newDatas && newDatas != "" && tools.isArray(newDatas)) {					
					if(newDatas.length>1&&option.show_jPagination){	
						var vPage=newDatas[0];
						if(vPage["curPage"])
							option.curPage=vPage["curPage"];
						else
							alert("not found return page object!");
						if(vPage["totalPageCount"])
							option.totalPageCount=vPage["totalPageCount"];		
						else
							alert("not found return page object!");
						newDatas.shift();
						if(newDatas.length==0)
							option.store=[];
						else
							option.store=newDatas;
					}else{
						option.store=newDatas;
					}
				} 				
				if($loading)
					$loading.hide();
				option.jGrid.ajaxing=false;				
				option.jGrid.trigger(LOAD_DATA_SUCCESS, [option.jGridObjId, obj, msg, newDatas]);

			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {				
				if($loading){	
					$loading.html('<div style="font-weight:bold;text-align:center;margin:0 auto;">read data error!</div>');
					setTimeout(function(){$loading.empty();$loading.hide();},2000);	
				}
				option.jGrid.ajaxing=false;	
				option.store=[];
				if(option.callback.asyncError)
					option.jGrid.trigger(LOAD_DATA_ERROR, [option.jGridObjId, obj, XMLHttpRequest, textStatus, errorThrown]);
			}
		});
	}	
	function setEvenOddTrCss(option){					
		jGrid=option.jGrid;
		if(!option.tbody)option.tbody=option.contentDiv.find("tbody:eq(0)");
		var $tbody=option.tbody;
		$trEven=$("tr:nth-child(even)",$tbody);
		$trOdd=$("tr:nth-child(odd)",$tbody);
		$trEven.removeClass(ODD_CLASS_NAME).addClass(EVEN_CLASS_NAME);
		$trOdd.removeClass(EVEN_CLASS_NAME).addClass(ODD_CLASS_NAME);				
	}
	function getSelectedIds(option){
		var $trs=option.jGrid.find("tr["+SELECTED_ATTR+"]["+BEAN_ID+"]");
		var trIdArray=new Array();
		$trs.each(function(){
			trIdArray.push($(this).attr(BEAN_ID));
		});
		return trIdArray.join(",");
	}
	function getAllSelectedIds(option){
		var $trs=option.jGrid.find("tr["+BEAN_ID+"]");
		var trIdArray=new Array();
		$trs.each(function(){
			trIdArray.push($(this).attr(BEAN_ID));
		});
		return trIdArray.join(",");
	}	
	function convert(sValue, sDataType) {
		switch(sDataType) {
			case "int": return parseInt(sValue);
			case "float": return parseFloat(sValue);
			case "date": return new Date(Date.parse(sValue));
			default: return sValue.toString();
		}
	}	
	function generateCompareTRs(iCol, sDataType) {
		return  function compareTRs(oTR1, oTR2) {
			var vValue1 = $.trim(convert($(oTR1).children().eq(iCol).text(), sDataType));
		  	var vValue2 = $.trim(convert($(oTR2).children().eq(iCol).text(), sDataType));
			
			if (vValue1 < vValue2) 
			  return -1;
			else if (vValue1 > vValue2)
			  return 1;
			else
			  return 0;			
		};
	}
	function sortTable(option, iCol, sDataType) {		
		$gridObj=option.jGrid;	  
		if(!option.tbody)option.tbody=option.contentDiv.find("tbody:eq(0)"); 
		var $tbody=option.tbody;
		var $tr= $("tr",$tbody);
		var aTRs = new Array;
		var cellEmptyTRs= new Array;	  
		var cellEmptyTRsCnt=0;
		var aTRsCnt=0;		
		$tr.each(function(i){		  
			tdText=$.trim($("td:eq("+iCol+")",this).text());		  				  
			if(tdText==""||tdText.charCodeAt(0)==160){
			  cellEmptyTRs[cellEmptyTRsCnt++]=$(this)[0];
			}
			else{
			  aTRs[aTRsCnt++] =$(this)[0];			
			}			
		});  		
		if ($gridObj.sortCol == iCol) {
			aTRs.reverse();
			if($gridObj.SORT_FLAG)
			  $gridObj.SORT_FLAG=false;
			else
			  $gridObj.SORT_FLAG=true;
		} else {			
			aTRs.sort(generateCompareTRs(iCol, sDataType));
			$gridObj.SORT_FLAG=true;
		}		
		$tbody.empty();
		$tbody.append(aTRs);
		$tbody.append(cellEmptyTRs);		
		$gridObj.sortCol = iCol;
	}
	function JGrid(){
		return{
			container:null,
			option:null,
			getSelectedBeanId:function(){
				return getSelectedIds(this.option);
			},
			init:function(obj,option){
				this.container = obj;
				this.option=option;
			},
			getCurPage:function(){
				var curPage=""+this.option.curPage;
				return curPage;
			},
			refreshTable:function(dataArray){
				if(dataArray&&tools.isArray(dataArray)){
					fillData(this.option,dataArray);
					setEvenOddTrCss(this.option);	
				}
			},				
			refreshPage:function(dataArray){				
				if(dataArray){
					var vPage=dataArray[0];
						if(vPage["curPage"])
							this.option.curPage=vPage["curPage"];
						else{
							alert("not found return page object!");
							return ;
						}
						if(vPage["totalPageCount"])
							this.option.totalPageCount=vPage["totalPageCount"];		
						else{
							alert("not found return page object!");						
							return ;
						}
						dataArray.shift();
						if(dataArray.length==0)
							this.option.store=[];
						else
							this.option.store=dataArray;						
				}
				else{
				
					asyncGetData(this.option);
				}
				renderPage(this.option);
				
			},
			reRenderGrid:function(dataArray){
				this.refreshPage(dataArray);
				this.refreshTable(dataArray);
			},
			getStore:function(){
				var store=new Array();
				for(var i in this.option.store)
				  store[i]=this.option.store[i];
				return store;
			},
			loadingShow:function(){
				if(this.option.loading)this.option.loading.show();	
			},
			loadingHide:function(){
				if(this.option.loading)this.option.loading.hide();	
			}			
		}
	}
	var tools = {
		apply: function(fun, param, defaultValue) {
			if ((typeof fun) == "function") {
				return fun.apply(tools, param);
			}
			return defaultValue;
		},
		eqs: function(str1, str2) {
			return str1.toLowerCase() === str2.toLowerCase();
		},
		isArray: function(arr) {
			return Object.prototype.toString.apply(arr) === "[object Array]";
		},
		clone: function (jsonObj) {
			var buf;
			if (jsonObj instanceof Array) {
				buf = [];
				var i = jsonObj.length;
				while (i--) {
					buf[i] = arguments.callee(jsonObj[i]);
				}
				return buf;
			}else if (typeof jsonObj == "function"){
				return jsonObj;
			}else if (jsonObj instanceof Object){
				buf = {};
				for (var k in jsonObj) {					
					buf[k] = arguments.callee(jsonObj[k]);					
				}
				return buf;
			}else{
				return jsonObj;
			}
		}
	}	
	function drawTitle(option){
		var ret='<div class="listTitle"><span class="titleFont">'+option.title+'</span></div>';
		return ret;
	}
	function drawButtonBar(option){
		if(!option.showButtonBar)return "";
		var ret='<div class="listButton">';
		if(option.buttons.add&&option.buttons.add.show)
			ret+='<input type="button" class="button add" value="'+option.buttons.add.text+'">';
		if(option.buttons.update&&option.buttons.update.show)
			ret+='<input type="button" class="button update" value="'+option.buttons.update.text+'">';
		if(option.buttons.remove&&option.buttons.remove.show)
			ret+='<input type="button" class="button remove" value="'+option.buttons.remove.text+'">';
		if(option.buttons.removeAll&&option.buttons.removeAll.show)
			ret+='<input type="button" class="button trash" value="'+option.buttons.removeAll.text+'">';
		if(option.buttons.search&&option.buttons.search.show)
			ret+='<input type="button" class="button search" value="'+option.buttons.search.text+'">';
		ret+=drawCustomButtons(option);
		ret+='</div>';		
		return ret;
	}
	function drawCustomButtons(option){
		var ret="";
		if(!option.customButtons||option.customButtons.length==0)return ret;
		for(var i in option.customButtons){			
			vClass=option.customButtons[i].className?option.customButtons[i].className:"";
			vActiveFunction=option.customButtons[i].activeFunction?option.customButtons[i].activeFunction:"";
			ret+='<input type="button" onClick="'+vActiveFunction+'" '+CUSTOM_BUTTON_CLASS_NAME+'="true" class="button '+vClass+'" value="'+option.customButtons[i].text+'">';
		}
		return ret;
	}
	function drawHeader(option){
		var ret='<table class="tableList tableListHeader" ><thead><tr class="thBg">';
		ret+=processHeader(option);
		ret+='</tr></thead></table>';
		return ret;
	}
	function drawContent(option){
		var ret='<div class="listContent"><div class="'+LOADING_CLASS_NAME+'"></div><table class="tableList" ><tbody>';
		ret+=drawEmptyLine(option);	
		ret+='</tbody></table></div>';
		return ret;
	}
	function drawJPagination(option){
		if(!option.show_jPagination&&option.show_jTable)
			return '<DIV class="topLine"></DIV>';
		return '<DIV id='+option.jPaginationId+' class="'+JPAGINATION_CLASS_NAME+'"></DIV>';
		
	}
	function drawEmptyLine(option,emptyLine){
		if(0==emptyLine)return "";
		if(!emptyLine)emptyLine=option.pageSize;
		var ret="";
		for(var r=0;r<emptyLine;r++){		
			ret+='<tr>';	
			for(c=0;c<option.jGrid.columnCount;c++){
				if(option.sn.show&&c==0)
				  ret+='<td width="'+option.sn.width+'"></td>';
				ret+='<td width="'+option.columns[c].width+'">&nbsp;</td>';
			}
			ret+='</tr>';
		}
		return ret;
	}
	function processPageHtml(option){
		var p=parseInt(option.curPage);
		var pn=parseInt(option.totalPageCount);
		var pageButtonCount=parseInt(option.pageButtonCount);
		if(pn<=1){p=1;pn=1;return drawCurrentPage(1);}
		if(pn<p){p=pn;};
		var re="";
		if(p<=1){
			p=1;
		}else{
			if(option.buttons.first.show){re+=drawPage(1,pn,option.buttons.first.text);}
			if(option.buttons.prev.show){re+=drawPage(p-1,pn,option.buttons.prev.text);}
			re+=drawPage(1,pn,"1");
		}

		var start=2;
		var end=(pn<pageButtonCount)?pn:pageButtonCount;
		var position=parseInt(pageButtonCount/2);
		if(p>=7){
			re+="<SPAN>...</SPAN>";
			start=p-position;			
			if(pageButtonCount%2==0)position-=1;
			var e=p+position;
			end=(pn<e)?pn:e;
			
		}
		for(var i=start;i<p;i++){
			re+=drawPage(i,pn);
		};
		re+=drawCurrentPage(p);
		for(var i=p+1;i<=end;i++){
			re+=drawPage(i,pn);
		};
		if(end<pn){re+="<SPAN>...</SPAN>";};
		if(p<pn){
			if(option.buttons.next.show)re+=drawPage(p+1,pn,option.buttons.next.text);
			if(option.buttons.last.show)re+=drawPage(pn,pn,option.buttons.last.text);
		};
		
		if(option.showPageInputText){
			re+=drawGoPage(option);
		}
		return re;
	}
	function drawPage(pageNo,pn,showPageNo){
		showPageNo=showPageNo||pageNo;
		var ret=" <a class='pageNumber' page='"+pageNo+"'>"+showPageNo+"</a> ";
		return ret;
	};
    function drawCurrentPage(pageNo){
		var ret=" <a class='currentPage' page='"+pageNo+"'>"+pageNo+"</a> ";
		return ret;
	};
	function drawGoPage(option){
		var ret=' &nbsp;<input class="pageTextfield" type="text" id="pageNumberText" /> &nbsp;<a class="go" >'+option.buttons.go.text+'</a>' ;
		return ret;
	}
	function fillForm(event,option,goTo,vTarget){
		var $target = $(event.target);
		
		$form=option.form;
		if(!$form){alert("not found form!");return false;}
		var	vPageHidden="";		
		$form.find("input[custom]").remove();		
		if(goTo){
			pageNumTxt=validatePageNumber(option);
			if(pageNumTxt==-1)return false;
			vPageHidden='<input type="hidden" name="'+option.curPageName+'" value="'+pageNumTxt+'" custom="true"/>';			
		}
		else
			vPageHidden='<input type="hidden" name="'+option.curPageName+'" value="'+$target.attr("page")+'"custom="true"/>';				
		
		vPageHidden+='<input type="hidden" name="'+option.pageSizeName+'" value="'+option.pageSize+'" custom="true"/>';
		if(option.params){
			for(var key in option.params){
				vPageHidden+='<input type="hidden" name="'+key+'" value="'+option.params[key]+'"custom="true"/>';
			}
		}		
		$form.append(vPageHidden);				
		return true;
	}
	function validatePageNumber(option){
		$pageNumberText=$("#pageNumberText");
		var vNum=$pageNumberText.val();
		if(!isNaN(vNum)){	
		 	if(vNum=="")
			  return -1;	
			if(vNum>option.totalPageCount)
			  return option.totalPageCount;
			else if(vNum<1)
			  return 1;				
			return vNum;	
		}
		return -1;
	}
	function fillData(option,dataArray){
		if(dataArray)
			option.store=dataArray;
		var emptyLine=option.pageSize-option.store.length;
		if(emptyLine<0)emptyLine=0;
		var ret="";
		for(var r=0;r<option.store.length;r++){
			beanIdValue=option.store[r][option.jGrid.idMapping];
			ret+='<tr '+BEAN_ID+'='+beanIdValue+'>';
			
			for(c=0;c<option.jGrid.columnCount;c++){
				if(option.sn.show&&c==0)
				  ret+='<td width="'+option.sn.width+'" align="center">'+(r+1)+'</td>';
				ret+='<td width="'+option.columns[c].width+'">'+option.store[r][option.columns[c].mapping]+'</td>';
			}
			ret+='</tr>';
		}
		ret+=drawEmptyLine(option,emptyLine);
		if(!option.tbody)option.tbody=option.contentDiv.find("tbody:eq(0)");
		option.tbody.empty().append(ret);
		
		return ret;
	}	
})(jQuery);	
 